package com.lanou.authcenter;


import com.lanou.authcenter.utils.LoginRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //确保本配置文件中shiroFilter在DispatcherServlet前启动,如果已经启动，则忽略。
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator def = new DefaultAdvisorAutoProxyCreator();
        def.setProxyTargetClass(true);
        return def;
    }

    //配置登陆用的Realm
    @Bean
    public LoginRealm getLoginRealm() {
        return new LoginRealm();
    }

    //配置shiro大管家SecurityManager
    @Bean
    public DefaultWebSecurityManager getSecurityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(getLoginRealm());
        return manager;
    }

    //配置shiro的Filter
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactory() {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(getSecurityManager());
        shiroFilter.setLoginUrl("/login.html");
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/**","anon");
        shiroFilter.setFilterChainDefinitionMap(map);
        return shiroFilter;
    }

    //让注解生效
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager ) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
